﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using Com.Alipay;

namespace AUV5.Web.Alipay
{
    public partial class Return_Url : PageBaseFrontend
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (base.IsVerified)
            {
                log.Debug("非异步");
                SortedDictionary<string, string> sPara = GetRequestGet();

                if (sPara.Count > 0)//判断是否有带返回参数
                {
                    Notify aliNotify = new Notify();
                    bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]);

                    if (verifyResult)//验证成功
                    {
                        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        //请在这里加上商户的业务逻辑程序代码


                        
                        //AUV5.BLL.OrderInfoBLL.Instance.Update(

                        //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
                        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表
                        string trade_no = Request.QueryString["trade_no"];              //支付宝交易号
                        string order_no = Request.QueryString["out_trade_no"];	        //获取订单号
                        string total_fee = Request.QueryString["total_fee"];            //获取总金额
                        string subject = Request.QueryString["subject"];                //商品名称、订单名称
                        string body = Request.QueryString["body"];                      //商品描述、订单备注、描述
                        string buyer_email = Request.QueryString["buyer_email"];        //买家支付宝账号
                        string trade_status = Request.QueryString["trade_status"];      //交易状态
                        string extra_common_param = Request.QueryString["extra_common_param"];   //自定义参数（服务ID）
                        string userIP = Request.UserHostAddress;  //客户端IDP   
                        string serviceId = string.Empty;
                        string userId = string.Empty;
                        if (!string.IsNullOrEmpty(extra_common_param))
                        {
                            string[] paramArr = paramArr = extra_common_param.Split('_');
                            serviceId = paramArr[0];
                            userId = paramArr[1];
                        }
                       
                        if (Request.QueryString["trade_status"] == "TRADE_FINISHED" || Request.QueryString["trade_status"] == "TRADE_SUCCESS")
                        {
                            //判断该笔订单是否在商户网站中已经做过处理
                            //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                            //如果有做过处理，不执行商户的业务程序

                            AUV5.Model.OrderInfo order = AUV5.BLL.OrderInfoBLL.Instance.GetOrderInfoByOrderCode(order_no);

                            if (order != null)
                            {
                                if (Convert.ToInt32(order.StatusID) < Convert.ToInt32(AUV5.Common.Enum.OrderState.Payment))
                                {
                                    order.StatusID = Convert.ToInt32(AUV5.Common.Enum.OrderState.Payment);

                                    order.Payment = Convert.ToDecimal(total_fee);

                                    order.IsLocalPayment = false;

                                    order.BeginDate = DateTime.Now;

                                    order.EndDate = AUV5.BLL.OrderInfoBLL.Instance.GetEndTimeByOrderCode(order_no);

                                    AUV5.BLL.OrderInfoBLL.Instance.UpdateOrderInfoByOrderCode(order);

                                    AUV5.Model.UserInfo buyerInfo = AUV5.BLL.UserInfoBLL.Instance.GetDetail(order.Buyer);

                                    if (buyerInfo != null)
                                    {
                                        AUV5.BLL.BulletinBLL.Instance.AddBulletin("订单提示", string.Format("买家{0}为订单付款成功", buyerInfo.UserName), order.Seller, false, Convert.ToInt32(AUV5.Common.Enum.bulletinStatus.BeSeller), order.OrderID);
                                    }                                    

                                    AUV5.Model.PaymentHistory history = new Model.PaymentHistory();
                                    history.HistoryId = Guid.NewGuid().ToString();
                                    history.IpAddress = userIP;
                                    history.OrderCode = order.OrderCode;
                                    history.PaymentAccount = buyer_email;
                                    history.ServiceId = serviceId;
                                    history.TotalFee = Convert.ToDecimal(total_fee);
                                    history.TradeNo = trade_no;
                                    history.TradeStatus = trade_status;
                                    history.UpdateDate = DateTime.Now;
                                    history.UserId = userId;
                                   

                                    //添加支付记录
                                    AUV5.BLL.PaymentHistoryBLL.GetInstance().Add(history);
                                }

                                Response.Write("<br />支付宝交易号:");
                                Response.Write(trade_no);
                                Response.Write("<br />订单号:");
                                Response.Write(order_no);
                                Response.Write("<br />总金额:");
                                Response.Write(total_fee);
                                Response.Write("<br />商品名称:");
                                Response.Write(subject);
                                Response.Write("<br />商品描述:");
                                Response.Write(body);
                                Response.Write("<br />买家支付宝账号:");
                                Response.Write(buyer_email);
                                Response.Write("<br />交易状态:");
                                Response.Write(trade_status);
                                Response.Write("<br />付款人IP:");
                                Response.Write(userIP);
                                Response.Write("<br />服务ID:");
                                Response.Write(serviceId);
                                Response.Write("<br />用户ID:");
                                Response.Write(userId);                                
                                Response.Write("<br />success");

                                Response.Redirect("/Pages/OrderResult.aspx?OrderID=" + order.OrderID);
                            }
                            else
                            {
                                log.Debug(order_no + "订单不存在");
                            }
                        }
                        else
                        {
                            Response.Write("trade_status=" + Request.QueryString["trade_status"]);
                        }

                        //打印页面

                        //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

                        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    }
                    else//验证失败
                    {
                        Response.Write("验证失败");
                    }
                }
                else
                {
                    Response.Write("无返回参数");
                }
            }
            else
            {
                Response.Redirect(URL_INDEX);
            }
        }

        /// <summary>
        /// 获取支付宝GET过来通知消息，并以“参数名=参数值”的形式组成数组
        /// </summary>
        /// <returns>request回来的信息组成的数组</returns>
        public SortedDictionary<string, string> GetRequestGet()
        {
            int i = 0;
            SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
            NameValueCollection coll;
            //Load Form variables into NameValueCollection variable.
            coll = Request.QueryString;

            // Get names of all forms into a string array.
            String[] requestItem = coll.AllKeys;

            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]);
            }

            return sArray;
        }

    }
}